package classes;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;


public class Test {

	private final static String URL_EMPRESAS = "http://www.bmfbovespa.com.br/pregao-online/ExecutaAcaoCotRapXSL.asp?intIdiomaXsl=3";
	private final static String URL_COTACAO = "http://www.bmfbovespa.com.br/Pregao-Online/ExecutaAcaoCarregarDadosPapeis.asp?CodDado=";
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		empresas();
		try {
			URLConnection connection = new URL(URL_COTACAO + "AMBV10").openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			
			String buffer = reader.readLine();		
			String[] info = buffer.split("&");
			String values = info[1].substring(2).replace('|', '&');
			for (String cotacao : values.split("&")) {
				System.out.println(cotacao);
			}
		} catch (Exception e) {
			//Log.e("carregarDadosPapeis", e.getLocalizedMessage());
		}

	}
	
	public static void empresas(){
		try {
			URLConnection connection = new URL(URL_EMPRESAS).openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			
			int tables = 0;
			List<String> source = new ArrayList<String>();
			String buffer = null;
			while ((buffer = reader.readLine()) != null) {
				if (buffer.startsWith("<table")) tables++;
				if (tables == 3) {
					if (buffer.startsWith("<font face=\"verdana\"")) source.add(buffer);
					if (buffer.startsWith("<td") && buffer.length() > 66) source.add(buffer);
					if (buffer.startsWith("</table>")) break;
				}
			}
			
			for (int i = 0; i < source.size(); i = i + 2) {
				String empresa = source.get(i).substring(37, source.get(i).length() - 7);
				String codigo = source.get(i + 1).substring(72, source.get(i + 1).indexOf("&"));
				if (codigo == null || empresa == null) continue;
				System.out.println(codigo +"-"+ empresa);
			}			
		} catch (Exception e) {
			//Log.e("carregarDadosPapeis", e.getLocalizedMessage());
		}
	}

}
